package com.ys.service.hr.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.TwlStock;
import com.ys.entity.hr.TwlStockBorrow;
import com.ys.entity.hr.TwlStockBorrowDetail;
import com.ys.entity.hr.TwlStockIn;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.hr.TwlStockBorrowDetailEnum;
import com.ys.mapper.hr.HrMapper;
import com.ys.mapper.hr.TwlStockBorrowDetailMapper;
import com.ys.mapper.hr.TwlStockBorrowMapper;
import com.ys.service.flow.YspTaskService;
import com.ys.service.hr.TwlStockBorrowService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

@Service("twlStockBorrowService")
public class TwlStockBorrowServiceImpl implements TwlStockBorrowService {

	@Autowired
	private HrMapper hrMapper;
	@Autowired
	private TwlStockBorrowMapper twlStockBorrowMapper;
	@Autowired
	private TwlStockBorrowDetailMapper twlStockBorrowDetailMapper;
	
	@Autowired
	private YspTaskService yspTaskService;
	
	/*
	 * 新增
	 */
	@Override
	public R add(String bid, String borrowUserId, String remark, String detailArr, Long menuId) throws Exception {
		
		if (bid == null || bid.length() == 0) {
			return R.error("单号不能为空");
		} else if(new TwlStockIn().setBid(bid).count() > 0) {
			return R.error("单号已存在");
		}
		
		/*
		 *  验证详情数据物料
		 *  1、编码不能为空
		 *  2、数量不能为空，且不能超过可用数量
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long stockId = detailJO.getLong("stockId");

			Integer num = detailJO.getInteger("num");
			if (num == null) {
				return R.error("数量不能为空");
			} else if (num <= 0) {
				return R.error("数量必须为正");
			}
			
			TwlStock twlStock = new TwlStock().setId(stockId).queryFirst();
			if (num > twlStock.getNumAll()) {
				return R.error("【" + stockId + "】总数量不足");
			}
		}
		
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		
		TsUserChange borrowUserChange = new TsUserChange().setUserId(borrowUserId).setStatus(1).queryFirst();
		
		// 添加借用单
		TwlStockBorrow entity = null;
		{
			Integer effectStock = FlowEnum.EffectStock.NOT_EFFECT.value;
			Long createChangeId = tsUserChange.getId();
			Long borrowChangeId = borrowUserChange.getId();
			entity = TwlStockBorrow.twlStockBorrow(bid, effectStock, createChangeId, borrowChangeId, remark, 1);
			twlStockBorrowMapper.insert(entity);
		}
		
		// 添加借用单明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long stockId = detailJO.getLong("stockId");
			if (stockId == null) {
				return R.error("库存ID不能为空");
			}

			Integer num = detailJO.getInteger("num");
			if (num == null) {
				return R.error("数量不能为空");
			} else if (num <= 0) {
				return R.error("数量必须为正");
			}
			
			String bidStockBorrow = bid;
			Integer state = TwlStockBorrowDetailEnum.State.NOT_BACK.value;
			Date rebakTime = null;
			TwlStockBorrowDetail twlStockBorrowDetail = TwlStockBorrowDetail.twlStockBorrowDetail(bidStockBorrow, stockId, num, state, rebakTime, 1);
			twlStockBorrowDetailMapper.insert(twlStockBorrowDetail);
		}
		
		/*
		 * 流程初始化
		 */
		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, bid, createUserId);
		}
		return R.ok(AddDto.gotoEdit("/web/hr/twlStockBorrow/toFlow?bid=" + bid));
	}
	
	@Override
	@Transactional
	public R edit(String bid, String borrowUserId, String remark, String detailArr, Long menuId) throws Exception {
		
		Integer stateFlow = yspTaskService.flowState(bid);
		if (stateFlow != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("非制单中数据，无法修改");
		}
		
		// 验证是否制单人
		YsProcInst entity = new YsProcInst().setBid(bid).queryFirst();
		if (!entity.getCreateUserId().equals(ShiroUtils.getUserId())) {
			return R.error("非制单人无法修改");
		}
		
		/*
		 *  验证详情数据物料
		 *  1、编码不能为空
		 *  2、数量不能为空，且不能超过可用数量
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long stockId = detailJO.getLong("stockId");

			Integer num = detailJO.getInteger("num");
			if (num == null) {
				return R.error("数量不能为空");
			} else if (num <= 0) {
				return R.error("数量必须为正");
			}
			
			TwlStock twlStock = new TwlStock().setId(stockId).queryFirst();
			if (num > twlStock.getNumAll()) {
				return R.error("【" + stockId + "】总数量不足");
			}
		}
		
		TsUserChange borrowUserChange = new TsUserChange().setUserId(borrowUserId).setStatus(1).queryFirst();
		
		TwlStockBorrow twlStockBorrow = new TwlStockBorrow().setBid(bid).queryFirst();
		twlStockBorrow.setBorrowChangeId(borrowUserChange.getId())
			.setRemark(remark);
		twlStockBorrowMapper.update(twlStockBorrow);
		
		// 删除旧的借用明细
		hrMapper.deleteTwlStockBorrowDetailByBid(bid);
		
		// 添加出库明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long stockId = detailJO.getLong("stockId");

			Integer num = detailJO.getInteger("num");
			
			String bidStockBorrow = bid;
			Integer state = TwlStockBorrowDetailEnum.State.NOT_BACK.value;
			Date rebakTime = null;
			TwlStockBorrowDetail twlStockBorrowDetail = TwlStockBorrowDetail.twlStockBorrowDetail(bidStockBorrow, stockId, num, state, rebakTime, 1);
			twlStockBorrowDetailMapper.insert(twlStockBorrowDetail);
		}
		
		return R.ok(EditDto.reloadPage("/web/hr/twlStockBorrow/toFlow?bid=" + bid));
	}

	@Override
	@Transactional
	public R deleteTrue(Long id) throws Exception {
		if (id == null) {
			return R.error("ID不能为空");
		}
		TwlStockBorrow entity = new TwlStockBorrow().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		
		if (!tsUserChange.getUserId().equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		
		// 删除主数据
		twlStockBorrowMapper.deleteTrue(id);
		
		// 删除子数据
		List<TwlStockBorrowDetail> listDetail = new TwlStockBorrowDetail().setBidStockBorrow(entity.getBid()).queryList();
		for(TwlStockBorrowDetail detail : listDetail) {
			twlStockBorrowDetailMapper.deleteTrue(detail.getId());
		}
		
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}

	@Override
	@Transactional
	public R flowPass(String bid, String loginUserId) throws Exception {
		
		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else {
				
				if (f.getState() == Flow.State.FINISH.value) {
					flowFinish(bid);
				}
				return R.ok();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	@Override
	public R flowRefuse(String bid, String reason, String loginUserId) throws Exception {
		
		R r = yspTaskService.flowRefuse(bid, reason, loginUserId);
		return r;
	}

	@Override
	@Transactional
	public void flowFinish(String bid) throws Exception {
		
		TwlStockBorrow entity = new TwlStockBorrow().setBid(bid).queryFirst();
		
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		twlStockBorrowMapper.update(entity);
	}


	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam(String bid) throws Exception{
		Map<String, Object> extraParam = new TwlStockBorrow().setBid(bid).queryFirstMap();

		Long borrowChangeId = Long.parseLong(extraParam.get("borrowChangeId").toString());
		TsUserChange tsUserChange = new TsUserChange().setId(borrowChangeId).queryFirst();
		extraParam.put("borrowUserId", tsUserChange.getUserId());
		extraParam.put("borrowOrgName", tsUserChange.getDeptName());

		return extraParam;
	}
	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList( String bid) throws Exception{
		List<Map<String, Object>> sonlist = new TwlStockBorrowDetail()
				.setBidStockBorrow(bid)
				.addLeftJoin("TWL_Stock B on B.Id = A.StockId")
				.addField("B.NumAll stockNum")
				.addField("B.StockInDay stockInDay")
				.addField("B.Remark stockRemark")
				.addField("DATEDIFF(DAY, B.StockInDay , getdate()) stockInDays")
				.addField("(SELECT ISNULL(SUM(AA.Num), 0) FROM TWL_StockBorrowDetail AA LEFT JOIN TWL_StockBorrow BB ON BB.Bid = AA.BidStockBorrow WHERE BB.EffectStock = 1 AND AA.StockId = B.Id) numBorrowed")

				.addLeftJoin("TWL_StockInDetail B1 on B1.Id = B.StockInDetailId")
				.addField("B1.Img img")
				.addField("B1.Price price")
				.addField("B1.BidStockIn bidStockIn")

				.addLeftJoin("TB_Material C on C.Code = B.MaterialCode")
				.addField("C.Code materialCode")
				.addField("C.Name materialName")
				.addField("C.Remark materialRemark")

				.addLeftJoin("TB_CompanyInfo D ON D.Vid = B.CompanyVid")
				.addField("D.Vname companyVname")
				.queryMap();
		return sonlist;
	}




}
